import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/search.dart';
import 'package:mall/core/models/store_product_query.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/view_model.dart';

class SearchProductModel extends ViewModel {
  final Api api;
  String _keyword;
  List<Product> _list = [];
  String _errorMessage;
  Search _search;

  SearchProductModel(this.api) : super();

  set keyword(String value) {
    debugPrint('$this keyword = $value');
    if (_keyword != value) {
      _keyword = value;
      _searchProduct();
    }
  }

  List<Product> get list => _list;

  String get errorMessage => _errorMessage;

  Search get search => _search;

  Future<ViewState> _searchProduct() async {
    viewState = ViewState.busy;
    try {
      _search = await api.search(_keyword, 0);
      _list.clear();
      _list.addAll(_search.models.content);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> loadData() async {
    try {
      _search = await api.search(_keyword, _list.length ~/ 10);
      _list.addAll(_search.models.content);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }
}
